#include "Common.h"
#include "Headers.h"

namespace Audio
{
	PlayingVoiceCommand::PlayingVoiceCommand(AudioPlayingVoice* p)
		:AudioCommand(p->GetVoice())
		,playingVoice(p)
	{

	}

	void CreateVoiceCommand::Do(IAudioDevice* device)
	{	
		if(sender && !sender->IsBad())
		{
			try
			{	
				sender->PreLoad();				
			}
			catch(const ExceptionBase& e)
			{
				sender->SetLastError(e.ErrorCode());
				return;
			}			
		}
	}

	void DestroyVoiceCommand::Do(IAudioDevice* device)
	{
		if(sender && !sender->IsBad())
		{
			try
			{
				delete sender;
			}
			catch(const ExceptionBase& e)
			{
				return;
			}
		}
	}

	void PlayCommand::Do(IAudioDevice* device)
	{
		if(sender && !sender->IsBad())
		{
			try
			{	
				IVoice* voice = device->CreateVoice(sender->GetInfo()
					, sender->GetInfoSize());
				playingVoice->SetInfo(voice);
				playingVoice->Start();	
			}
			catch(const ExceptionBase& e)
			{
				sender->SetLastError(e.ErrorCode());
				return;
			}					
		}
	}

	void StopCommand::Do(IAudioDevice* device)
	{
		if(playingVoice && !playingVoice->IsBad())
		{
			try
			{
				playingVoice->Stop();
			}
			catch(const ExceptionBase& e)
			{
				playingVoice->SetLastError(e.ErrorCode());
				return;
			}	
		}
	}

	void LoadDataCommand::Do(IAudioDevice* device)
	{
		if(playingVoice && !playingVoice->IsBad())
		{
			try
			{
				if(playingVoice->IsAllDataSubmited())
				{
					playingVoice->PlayingCompleted();
					AudioManager::Get()->DestoyAudioPlayingVoice(playingVoice);
				}
				else
				{
					playingVoice->LoadData();
				}
			}			
			catch(const ExceptionBase& e)
			{
				playingVoice->SetLastError(e.ErrorCode());
				return;
			}	
		}
	}

	void InitDeviceCommand::Do(IAudioDevice* device)
	{
		try
		{
			device->Init();
		}
		catch(const ExceptionBase& e)
		{
			device->SetLastError(e.ErrorCode());
			return;
		}
	}

	void DestroyDeviceCommand::Do(IAudioDevice* device)
	{
		try
		{
			if(device && !device->IsBad())
			{
				device->Destroy();
			}
		}		
		catch(const ExceptionBase& e)
		{
			device->SetLastError(e.ErrorCode());
			return;
		}
		
	}

	void EndAudioThreadCommand::Do(IAudioDevice* device)
	{
		throw EndAudioThreadException();
	}

	void SetVolumeCommand::Do(IAudioDevice* device)
	{
		if(playingVoice && !playingVoice->IsBad())	
		{
			playingVoice->SetVolume(volume);
		}
	}

	void ResumeCommand::Do(IAudioDevice* device)
	{
		if(playingVoice && !playingVoice->IsBad())
		{
			playingVoice->Resume();
		}
	}

}
